using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

[CreateAssetMenu(fileName = "UIVariableTypeMapping", menuName = "UI/变量类型映射配置")]
/// <summary>
/// UIVariableGenerator 的短名到完整类型名映射配置
/// </summary>
public class UIVariableTypeMappingConfig : ScriptableObject
{
    [Serializable]
    public class Entry
    {
        public string Key;
        public string FullType;
    }

    public List<Entry> Entries = new List<Entry>();

    public static List<Entry> GetDefaultEntries()
    {
        return new List<Entry>
        {
            // Unity
            new Entry{ Key = "Go", FullType = "GameObject"},
            new Entry{ Key = "Tsf", FullType = "Transform"},
            new Entry{ Key = "RTsf", FullType = "RectTransform"},
            new Entry{ Key = "Img", FullType = "Image"},
            new Entry{ Key = "RawImg", FullType = "RawImage"},
            new Entry{ Key = "Txt", FullType = "Text"},
            new Entry{ Key = "Btn", FullType = "Button"},
            new Entry{ Key = "VLG", FullType = "VerticalLayoutGroup"},
            new Entry{ Key = "HLG", FullType = "HorizontalLayoutGroup"},
            new Entry{ Key = "Tg", FullType = "Toggle"},
            new Entry{ Key = "TgG", FullType = "ToggleGroup"},
            new Entry{ Key = "Sli", FullType = "Slider"},
            new Entry{ Key = "SR", FullType = "ScrollRect"},
            new Entry{ Key = "IF", FullType = "InputField"},
            new Entry{ Key = "CSF", FullType = "ContentSizeFitter"},
            new Entry{ Key = "Dd", FullType = "Dropdown"},
            new Entry{ Key = "Anim", FullType = "Animator"},
            new Entry{ Key = "SBar", FullType = "Scrollbar"},
            new Entry{ Key = "CG", FullType = "CanvasGroup"},

            // 插件
            new Entry{ Key = "SA", FullType = "SkeletonAnimation"},
            new Entry{ Key = "SG", FullType = "SkeletonGraphic"},

            // 自定义扩展
            new Entry{ Key = "Pro", FullType = "UGUIProgress"},
            new Entry{ Key = "LBtn", FullType = "UGUILongButton"},
            new Entry{ Key = "UrlImg", FullType = "UIUrlImage"},
        };
    }

    public Dictionary<string, string> ToDictionary()
    {
        // 允许后面的条目覆盖前面的同名键
        return Entries
            .Where(e => !string.IsNullOrEmpty(e.Key) && !string.IsNullOrEmpty(e.FullType))
            .GroupBy(e => e.Key)
            .ToDictionary(g => g.Key, g => g.Last().FullType);
    }

#if UNITY_EDITOR
	// 当资产被创建、反序列化或在 Inspector 中发生变化时调用
	private void OnValidate()
	{
		// 若为空则自动填充默认映射（避免打扰已有自定义）
		if (Entries == null || Entries.Count == 0)
		{
			Entries = GetDefaultEntries();
			UnityEditor.EditorUtility.SetDirty(this);
			UnityEditor.AssetDatabase.SaveAssets();
		}
	}

	[ContextMenu("填充默认映射")]
	private void FillDefaultEntries()
	{
		Entries = GetDefaultEntries();
		UnityEditor.EditorUtility.SetDirty(this);
		UnityEditor.AssetDatabase.SaveAssets();
	}
#endif
}


